using abilities.parameters;
using LitJson;

namespace abilities.triggers.conditions
{
    public enum ParameterValueType
    {
        Absolute,
        Relative
    };

    public class AbilityTriggerConditionParameterValue : AbilityTriggerCondition
    {
        public int valueMin;
        public int valueMax;
        public ParameterValueType valueType;
        public string paramName;
        ParameterEntry _parameterEntry;

        public override bool FromJson(JsonData value)
        {
            if ("RELATIVE" == (string)value["valueType"])
            {
                valueType = ParameterValueType.Relative;
            }
            else
            {
                valueType = ParameterValueType.Absolute;
            }

            valueMin = value.ContainsKey("valueMin") ? (int)value["valueMin"] : -1;
            valueMax = value.ContainsKey("valueMax") ? (int)value["valueMax"] : -1;
            paramName = (string)value["paramName"];
            return true;
        }


        public override bool Check(AbilityContext context)
        {
            int value = 0;
            UnitObject owner = context.AbilityManager.Owner;
            if (_parameterEntry == null)
                _parameterEntry = ParameterEntry.GetByName(paramName);
            if (valueType == ParameterValueType.Relative)
            {
                value = (int) (owner.Parameter.GetCurrent(_parameterEntry) * 100.0f / owner.Parameter.GetBase(_parameterEntry));
            }
            else if (valueType == ParameterValueType.Absolute)
            {
                value = owner.Parameter.GetCurrent(_parameterEntry);
            }

            return checkResult(value);
        }

        bool checkResult(int value)
        {
            bool result = true;
            if (valueMin >= 0)
            {
                result = value >= valueMin;
            }

            if (result && valueMax >= 0)
            {
                result = value <= valueMax;
            }

            return result;
        }
    }
}